package juc;

import java.util.concurrent.CountDownLatch;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/30
 * Time:9:44
 * 计数器示例
 **/
public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        //创建计数器
        CountDownLatch latch = new CountDownLatch(5);//声明计数器初始值为5

        for (int i = 1; i < 6; i++) {
            final int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"开始起跑");
                    try {
                        Thread.sleep(finalI*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"到达终点");
                    //将计数器-1
                    latch.countDown();
                }
            }).start();
        }
        //阻塞等待
        latch.await();//当计数器减为0的时候，才会执行await之后的代码

        System.out.println("所有人都到达终点，公布排名");
    }
}
